package com.learning.mymedia;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;

import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;

public class MediaTest extends AppCompatActivity {
    private MediaRecorder recorder;
    private MediaPlayer player;
    private Uri fileUri; // 保存录音文件的 Uri
    private boolean isRecording = false; // 记录是否正在录音
    private boolean isPaused = false; // 记录是否暂停录音
    private boolean isPlaying = false; // 记录是否暂停播放
    private long startTime = 0; // 记录录音开始的时间
    private long pauseTime = 0; // 记录录音暂停的时间
    private long resumeTime = 0; // 记录录音继续的时间
    private long noTime = 0; // 记录录音暂停的持续的时间
    private Handler handler = new Handler(); // 用于更新录音时长
    private BottomSheetDialog bottomSheetDialog, bottomSheetDialog1; // 底部录音控制框
    private TextView recordingTimeTextView, playingTimeTextView; // 录音时长文本
    private Button pauseButton, pausePlayingButton; // 暂停按钮
    private Runnable updateRecordingTimeRunnable; // 用于更新录音时长的Runnable
    private String currentFileName; // 当前录音文件名称
    private ActivityResultLauncher<Intent> selectAudioFileLauncher;
    private long currentDuration;
    private Uri audioUri;
    private TextView tvFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_media_test);

        // 初始化 ActivityResultLauncher
        selectAudioFileLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        Intent data = result.getData();
                        if (data != null && data.getData() != null) {
                            audioUri = data.getData();
                            DocumentFile documentFile = DocumentFile.fromSingleUri(this, audioUri);
                            tvFileName.setText(documentFile.getName());
                            startPlaying(audioUri);
                        }
                    }
                }
        );


        // 获取按钮引用
        Button startRecordButton = findViewById(R.id.btn_start_record);
        Button startPlayButton = findViewById(R.id.btn_start_play);


        // 设置按钮点击事件
        startRecordButton.setOnClickListener(v -> showRecordingBottomSheet());
        startPlayButton.setOnClickListener(v -> showPlayingBottomSheet());


    }

    // 显示录音底部弹窗
    private void showRecordingBottomSheet() {
        // 使用 BottomSheetDialog 作为录音控制面板
        bottomSheetDialog = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.recording_bottom_sheet, null);
        bottomSheetDialog.setContentView(view);

        Button stopRecordingButton = view.findViewById(R.id.btn_stop_recording); //暂停
        Button cancelRecordingButton = view.findViewById(R.id.btn_cancel_recording); //取消
        pauseButton = view.findViewById(R.id.btn_pause_recording);
        recordingTimeTextView = view.findViewById(R.id.recording_time_text_view);

        // 开始录音
        startRecording();

        // 设置“暂停录音”按钮点击事件
        pauseButton.setOnClickListener(v -> {
            if (isPaused) {
                resumeRecording(); // 继续录音
            } else {
                pauseRecording(); // 暂停录音
            }
        });

        // 设置“取消录音”按钮点击事件
        cancelRecordingButton.setOnClickListener(v -> cancelRecording());

        // 设置“保存录音”按钮点击事件
        stopRecordingButton.setOnClickListener(v -> showSaveRecordingDialog());


        bottomSheetDialog.show();
    }

    // 开始录音，并在底部显示录音时长
    private void startRecording() {
        isRecording = true;
        isPaused = false;
        // 创建新的录音文件
        currentFileName = getExternalCacheDir().getAbsolutePath() + "/temp_record_" + System.currentTimeMillis() + ".3gp";

        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 设置音频源为麦克风
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); // 设置输出格式
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 设置音频编码
        recorder.setOutputFile(currentFileName);

        try {
            recorder.prepare();
            recorder.start(); // 开始录音
            startTime = System.currentTimeMillis(); // 记录录音开始时间
            updateRecordingTime(); // 开始更新录音时长

//            Toast.makeText(this, "开始录音", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 更新录音时长的逻辑
    private void updateRecordingTime() {
        updateRecordingTimeRunnable = new Runnable() {
            @Override
            public void run() {
                if (isRecording && !isPaused) {
                    long elapsedTime = System.currentTimeMillis() - startTime - noTime;
//                    int ms = (int) (elapsedTime / 1000);
                    int seconds = (int) (elapsedTime / 1000) % 60;
                    int minutes = (int) (elapsedTime / (1000 * 60)) % 60;
                    int hours = (int) (elapsedTime / (1000 * 60 * 60)) % 24;


                    // 更新录音时长显示
                    recordingTimeTextView.setText(String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds));

                    // 每隔1秒更新一次
                    handler.postDelayed(this, 1000);
                }
            }
        };

        handler.post(updateRecordingTimeRunnable); // 启动更新
    }


    // 暂停录音
    private void pauseRecording() {
        if (recorder != null && isRecording) {
            recorder.pause(); // 暂停录音
            isPaused = true;
            pauseTime = System.currentTimeMillis();
            pauseButton.setText("继续录音");
            handler.removeCallbacks(updateRecordingTimeRunnable); // 停止更新时长
        }
    }

    // 继续录音
    private void resumeRecording() {
        if (recorder != null && isRecording) {
            resumeTime = System.currentTimeMillis();
            noTime += resumeTime - pauseTime;
            recorder.resume(); // 恢复录音
            isPaused = false;
            pauseButton.setText("暂停录音");
            updateRecordingTime(); // 重新启动时长更新
        }
    }


    // 取消录音
    private void cancelRecording() {
        if (recorder != null && isRecording) {
            recorder.stop(); // 停止录音
            recorder.release();
            recorder = null;
            isRecording = false;
            isPaused = false;
            handler.removeCallbacks(updateRecordingTimeRunnable); // 停止更新时长

            // 删除临时文件
            File tempFile = new File(currentFileName);
            if (tempFile.exists()) {
                tempFile.delete();
            }

            bottomSheetDialog.dismiss(); // 关闭录音界面
            Toast.makeText(this, "录音已取消", Toast.LENGTH_SHORT).show();
        }
    }

    // 弹出保存录音的对话框，要求用户输入文件名
    private void showSaveRecordingDialog() {
        pauseRecording();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("保存录音");

        // 创建一个 LinearLayout 来包裹 EditText，并设置内边距
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(40, 40, 40, 40); // 设置内边距

        // 设置输入框
        final EditText input = new EditText(this);
        input.setText("请输入录音名称");
        layout.addView(input);
        builder.setView(layout);

        builder.setPositiveButton("确认", (dialog, which) -> {
            String fileName = input.getText().toString().trim();
            if (!fileName.isEmpty()) {
                saveRecording(fileName);
            } else {
                Toast.makeText(this, "文件名不能为空", Toast.LENGTH_SHORT).show();


            }
        });

        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        builder.show();
    }

    // 保存录音到 MediaStore 并指定用户输入的文件名
    private void saveRecording(String fileName) {
        // 停止录音
        if (recorder != null && isRecording) {
            recorder.stop();
            recorder.release();
            recorder = null;
            isRecording = false;
        }

        handler.removeCallbacks(updateRecordingTimeRunnable); // 停止更新时长
        bottomSheetDialog.dismiss(); // 关闭录音界面

        // 使用 MediaStore 进行保存
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Media.DISPLAY_NAME, fileName + ".mp3");
        values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mpeg");

        ContentResolver resolver = getContentResolver();
        Uri collection;

        // 根据不同的 API 级别选择保存位置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/Recordings/");
            collection = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
        } else {
            collection = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        Uri newUri = resolver.insert(collection, values);

        try {
            if (newUri != null) {
                // 将临时文件复制到目标位置
                ParcelFileDescriptor pfd = resolver.openFileDescriptor(newUri, "w");
                if (pfd != null) {
                    File tempFile = new File(currentFileName);
                    try (FileInputStream fis = new FileInputStream(tempFile);
                         FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor())) {
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = fis.read(buffer)) > 0) {
                            fos.write(buffer, 0, length);
                        }
                    }
                    tempFile.delete(); // 删除临时文件
                    Toast.makeText(this, "录音已保存", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    // 显示播放底部弹窗

    private void showPlayingBottomSheet() {
        // 使用 BottomSheetDialog 作为录音控制面板
        bottomSheetDialog1 = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.playing_bottom_sheet, null);
        bottomSheetDialog1.setContentView(view);

        Button selectFile = view.findViewById(R.id.btn_select_file);
        pausePlayingButton = view.findViewById(R.id.btn_pause_playing); //暂停
        Button exitPlayingButton = view.findViewById(R.id.btn_exit_playing); //取消
//        playingTimeTextView = view.findViewById(R.id.playing_time_text_view);
        tvFileName = view.findViewById(R.id.tv_file_name);


        selectFile.setOnClickListener(v -> {
            if (player != null) {
                player.release();
                player = null;
            }
            selectAudioFile();
        });

        // 设置“暂停”按钮点击事件
        pausePlayingButton.setOnClickListener(v -> {
            if (isPaused) {
                resumePlaying(); // 继续录音
            } else {
                pausePlaying(); // 暂停录音
            }
        });

        exitPlayingButton.setOnClickListener(v -> {
            stopPlaying();
        });


        bottomSheetDialog1.show();
    }

    // 启动文件选择器
    private void selectAudioFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/Music/Recordings/*");
        selectAudioFileLauncher.launch(intent);
    }


    private void startPlaying(Uri uri) {
        isPlaying = true;
        isPaused = false;
        if (uri != null) {
            player = new MediaPlayer();
            try {
                player.setDataSource(this, uri);
                player.prepare();
                player.start();
                Toast.makeText(this, "开始播放", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    private void pausePlaying() {
        if (player != null && isPlaying) {
            player.pause();
            pausePlayingButton.setText("继续播放");
            isPaused = true;
            currentDuration = player.getCurrentPosition();
        }
    }

    private void resumePlaying() {
        if (player != null && isPlaying) {
            player.seekTo((int) currentDuration);
            player.start(); // 恢复录音
            isPaused = false;
            pausePlayingButton.setText("暂停播放");
        }

    }

    private void stopPlaying() {
        if (player != null) {
            player.release();
            player = null;
            Toast.makeText(this, "停止播放", Toast.LENGTH_SHORT).show();
            bottomSheetDialog1.dismiss();
        }
    }

}